;(function(){
var role = require("./role");
var BusCon = require("../../core/bus/_con");
var UserCon = require("../../core/user/_con");
var GoodsCon = require("../../core/goods/_con");
var AchCon = require("../../core/ach/_con");
var db = require("../../core/db/index");
var config = require("../../core/_include/config");
var ResponObj = require("../_include/ResponObj");
var UserAddressCon = require("../../core/user_address/_con");
module.exports = {
	prefix:"/user/address",
	get:{
		//获取当前用户的地址信息(ID)列表
		"/":function *(){
			try{
				var user  = role.getUser(this);
			}catch(errorMsg){
				this.body = ResponObj("error",errorMsg);
				return;
			}
			var num = (+this.params.num)||5;
			var userAddresses = user.getAddress(num);
			this.body = ResponObj("json",userAddresses);
		},
		//获取当前用户的地址详细信息列表
		"/detail":function *(){
			try{
				var user  = role.getUser(this);
			}catch(errorMsg){
				this.body = ResponObj("error",errorMsg);
				return;
			}
			var num = (+this.params.num)||5;
			var userAddresses = user.getAddress(num);
			userAddresses.forEach(function(ua_id,index){
				userAddresses[index] = UserAddressCon.get(ua_id);
			});
			this.body = ResponObj("json",userAddresses);
		},
		//获取默认收获地址的详细信息
		"/default":function*(){
			try{
				var user  = role.getUser(this);
			}catch(errorMsg){
				this.body = ResponObj("error",errorMsg);
				return;
			}
			this.body = ResponObj("json",user.default_ua_id&&UserAddressCon.get(user.default_ua_id));
		}
	},
	post:{
		//为当前用户 添加 收获地址
		"/":function*(){
			try{
				var user  = role.getUser(this);
			}catch(errorMsg){
				this.body = ResponObj("error",errorMsg);
				return;
			}
			try{
				//无需判断重复，用户自行删除
				var ua = new UserAddressCon(this.request.body);
				user.addAddress(ua._id);
				this.body = ResponObj("json","成功添加新的收货地址");
			}catch(e){
				this.body = ResponObj("error",e);
			}
		}
	},
	"delete":{
		"/":function *(){
			try{
				var user  = role.getUser(this);
			}catch(errorMsg){
				this.body = ResponObj("error",errorMsg);
				return;
			}
			var address_id = this.request.body.address_id;
			if(user.removeAddress(address_id)){
				this.body = ResponObj("json","已成功删除本条收货地址");
			}else{
				this.body = ResponObj("error","找不到指定收货地址");
			}
		}
	},
	put:{
		"/default":function *(){
			try{
				var user  = role.getUser(this);
			}catch(errorMsg){
				this.body = ResponObj("error",errorMsg);
				return;
			}
			var default_ua_id = this.request.body.address_id;
			try{
				user.setDefaultAddress(default_ua_id);
				this.body = ResponObj("json","设置默认收货地址成功");
			}catch(e){
				this.body = ResponObj("error",e)
			}
		}
	}
}	
}());